package com.ruoyi.business.service.impl;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.ruoyi.business.BO.*;
import com.ruoyi.business.VO.*;
import com.ruoyi.business.service.HSPatientInfoService;
import io.swagger.models.auth.In;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class HSPatientInfoServiceImpl implements HSPatientInfoService {
    private final static String URL =  "http://27.128.173.8:10082";

    /**
     * 患者列表
     * **/
    @Override
    public PatientInfoListVO selectPatientInfoList(PatientInfo patientInfo) {

        String url = URL + "/patients_list";
        OkHttpClient client = new OkHttpClient().newBuilder()
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            String jsonBody = objectMapper.writeValueAsString(patientInfo);
            RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json; charset=utf-8"));
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .addHeader("Content-Type", "application/json; charset=utf-8")
                    .build();

            try (Response response = client.newCall(request).execute()) {
                String responseResult = response.body().string();
                // 将响应结果转换为 PatientInfoListVO 对象
                PatientInfoListVO apiResponse = objectMapper.readValue(responseResult, PatientInfoListVO.class);
                List<PatientInfoListVO.Patient> patientList = apiResponse.getResult();
                for(PatientInfoListVO.Patient patient : patientList) {

                    String birthDateStr = patient.getBirthDate();
                    // 定义日期格式
                    SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
                    // 解析输入日期
                    Date date = inputFormat.parse(birthDateStr);
                    // 格式化输出日期
                    String outputDate = outputFormat.format(date);
                    patient.setBirthDate(outputDate);

                    List<Map<String, String>> tabList = patient.getTab();
                    List<Map<String, String>> mapList = new ArrayList<>();

                    for(Map<String, String> tab : tabList) {

                        if(null != tab.get("患者类型")) {
                            Map<String, String> map = new HashMap<>();
                            map.put("key", "患者类型");
                            map.put("value", tab.get("患者类型"));
                            mapList.add(map);

                        }
                        if(null != tab.get("长期类型")) {
                            Map<String, String> map = new HashMap<>();
                            map.put("key", "长期类型");
                            map.put("value", tab.get("长期类型"));
                            mapList.add(map);
                        }

                    }
                    patient.setTag(mapList);
                }

                return apiResponse;  // 返回响应
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 患者详情
     * TUDO：优化
     * **/
    @Override
    public PatientInfoVO selectPatientInfoById(String idcard) {
        String url = URL + "/specificPatient";
        OkHttpClient client = new OkHttpClient().newBuilder()
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("idcard", idcard);
            map.put("topredict", 1);
            String jsonBody = objectMapper.writeValueAsString(map);
            RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json; charset=utf-8"));
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .addHeader("Content-Type", "application/json; charset=utf-8")
                    .build();
            try (Response response = client.newCall(request).execute()) {
                String responseResult = response.body().string();
                PatientInfoVO apiResponse = objectMapper.readValue(responseResult, PatientInfoVO.class);
                List<PatientInfoVO.Result.MedicalHistory> medicalHistoryList = apiResponse.getResult().getMedicalHistory();
                // TUDO：优化诊断整体状态
                for(PatientInfoVO.Result.MedicalHistory medicalHistory : medicalHistoryList) {
                    List<PatientInfoVO.Result.MedicalHistory.RecordDetail> recordDetailList = medicalHistory.getRecordDetail();
                    for(PatientInfoVO.Result.MedicalHistory.RecordDetail recordDetail : recordDetailList) {
                        List<PatientInfoVO.Result.MedicalHistory.RecordDetail.RecordDetailVile> recordDetailVileList = recordDetail.getRecordDetailVile();
                        for(PatientInfoVO.Result.MedicalHistory.RecordDetail.RecordDetailVile recordDetailVile : recordDetailVileList) {
                            if(1 == recordDetailVile.getStatus()) {
                                recordDetail.setDiagnosiStatus(1);
                            }
                        }
                    }
                }

                  apiResponse.getResult().getMedicalHistory().sort((history1, history2)->{
                    return history2.getMedicalDate().compareTo(history1.getMedicalDate());
                });

                return apiResponse;  // 返回响应
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 分项估计
     * **/
    @Override
    public DetailedAssessmentVO selectDetailedAssessment(DetailedAssessmentBO detailedAssessmentBO) {
        String url = URL + "/detailedAssessment";
        OkHttpClient client = new OkHttpClient().newBuilder()
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String jsonBody = objectMapper.writeValueAsString(detailedAssessmentBO);
            RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json; charset=utf-8"));
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .addHeader("Content-Type", "application/json; charset=utf-8")
                    .build();

            try (Response response = client.newCall(request).execute()) {
                String responseResult = response.body().string();
                ObjectMapper objectMapper1 = JsonMapper.builder()
                        .enable(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS) // 启用非数值数据
                        .build();
                // 将响应结果转换为 PatientInfoListVO 对象
                DetailedAssessmentVO apiResponse = objectMapper1.readValue(responseResult, DetailedAssessmentVO.class);
                List<DetailedAssessmentVO.SomeData> someDataList = apiResponse.getResult().getSome_data();

                if(null != someDataList) {
                    for(DetailedAssessmentVO.SomeData someData : someDataList) {
                        if(someData.getValue().equals("NaN") || someData.getValue().contains("nan")) {
                            someData.setValue("暂无");
                        }
                    }
                }
                if(null != apiResponse.getResult().getSix()) {
                    List<Map<String, Object>> mapList = new ArrayList<>();
                    Map<String, String> map = apiResponse.getResult().getSix();
                    for(String key : map.keySet()) {
                        Map<String, Object> map1 = new HashMap<>();
                        map1.put("key", key);
                        map1.put("value", Integer.parseInt(map.get(key)));
                        mapList.add(map1);
                    }
                    apiResponse.getResult().setSixMap(mapList);
                }
                return apiResponse;  // 返回响应
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public HealthServicesChinaparVO selectHealthServicesChinapar(HealthServicesChinaparBO healthServicesChinaparBO) {

        String url = URL + "/healthServices_chinapar";
        OkHttpClient client = new OkHttpClient().newBuilder()
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String jsonBody = objectMapper.writeValueAsString(healthServicesChinaparBO);
            RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json; charset=utf-8"));
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .addHeader("Content-Type", "application/json; charset=utf-8")
                    .build();

            try (Response response = client.newCall(request).execute()) {
                String responseResult = response.body().string();
                HealthServicesChinaparVO apiResponse = objectMapper.readValue(responseResult, HealthServicesChinaparVO.class);

                return apiResponse;  // 返回响应
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public HealthServicesDiabetesVO selectHealthServicesDiabetes(HealthServicesDiabetesBO healthServicesDiabetesBO) {
        String url = URL + "/healthServices_diabetes";
        OkHttpClient client = new OkHttpClient().newBuilder()
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String jsonBody = objectMapper.writeValueAsString(healthServicesDiabetesBO);
            RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json; charset=utf-8"));
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .addHeader("Content-Type", "application/json; charset=utf-8")
                    .build();

            try (Response response = client.newCall(request).execute()) {
                String responseResult = response.body().string();
                HealthServicesDiabetesVO apiResponse = objectMapper.readValue(responseResult, HealthServicesDiabetesVO.class);
                List<HealthServicesDiabetesVO.Result.SomeData> someDataList = apiResponse.getResult().getSome_data();
                for(HealthServicesDiabetesVO.Result.SomeData someData : someDataList) {
                    if(someData.getValue().equals("NaN") || someData.getValue().contains("nan")) {
                        someData.setValue("暂无");
                    }

                }
                return apiResponse;  // 返回响应
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public HealthServicesFattyliverVO selectHealthServicesFattyliver(HealthServicesFattyliverBO healthServicesFattyliverBO) {
        String url = URL + "/healthServices_fattyliver";
        OkHttpClient client = new OkHttpClient().newBuilder()
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String jsonBody = objectMapper.writeValueAsString(healthServicesFattyliverBO);
            RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json; charset=utf-8"));
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .addHeader("Content-Type", "application/json; charset=utf-8")
                    .build();

            try (Response response = client.newCall(request).execute()) {
                String responseResult = response.body().string();

                // 配置 ObjectMapper
                ObjectMapper objectMapper1 = JsonMapper.builder()
                        .enable(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS) // 启用非数值数据
                        .build();
                HealthServicesFattyliverVO apiResponse = objectMapper1.readValue(responseResult, HealthServicesFattyliverVO.class);
                List<HealthServicesFattyliverVO.Result.SomeData> someDataList = apiResponse.getResult().getSome_data();
                for(HealthServicesFattyliverVO.Result.SomeData someData : someDataList) {
                    if(someData.getValue().equals("NaN") || someData.getValue().contains("nan")) {
                        someData.setValue("暂无");
                    }

                }

                return apiResponse;  // 返回响应
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 健康服务-肝纤维化
     * **/
    @Override
    public HealthServicesFibVO selectHealthServicesFib(HealthServicesFibBO healthServicesFibBO) {
        String url = URL + "/healthServices_fib";
        OkHttpClient client = new OkHttpClient().newBuilder()
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String jsonBody = objectMapper.writeValueAsString(healthServicesFibBO);
            RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json; charset=utf-8"));
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .addHeader("Content-Type", "application/json; charset=utf-8")
                    .build();

            try (Response response = client.newCall(request).execute()) {
                String responseResult = response.body().string();

                // 配置 ObjectMapper
                HealthServicesFibVO apiResponse = objectMapper.readValue(responseResult, HealthServicesFibVO.class);

                return apiResponse;  // 返回响应
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
